from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests,functools
from application.models.users.user import *
from tools.Myjwt import myjwt
u_blue = Blueprint("ublue",__name__)


@u_blue.route("/getWBurl")
def getWBurl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code": 200, "url": url})


@u_blue.route("/weiboCallback/")
def weiboCallback():
    code = request.args.get('code')
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 解析参数,token,uid
    mes = json.loads(res.text)
    token = mes['access_token']
    uid = mes['uid']
    # 查询三方登录中uid是否存在，如果存在，查询用户表，用用户信息生成token跳转到vue页面
    sql = "select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid='%s'" % (uid)
    user = db.session.execute(sql)
    if user:
        for i in user:
            data = {"data": {"userid": i[0], "exp": int(time.time())}}
            token = myjwt.jwt_encode(data)
            return redirect("http://localhost:8080/#/updataToken?userid=" + str(i[0]) + "&token=" + token)
    # 不存在跳转到vue绑定页面， token，uid传递过去
    return redirect("http://localhost:8080/#/bindMobile?uid=" + uid + "&token=" + token)


@u_blue.route("/bindMobile", methods=["POST"])
def bindMobile():
    data = json.loads(request.data)
    mobile = data["mobile"]
    uid = data["uid"]
    token = data["token"]
    # 先查询用户表，如果手机号存在
    user = User.query.filter(User.mobile == mobile).first()
    if not user:
        # 添加用户
        u = User(mobile=mobile, nikename=mobile)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile == mobile).first()

    sfuser = SfLogin(userid=user.id, webfrom='wb', uid=uid, token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 如果不存在，写入user表
    # 获取userid，写入三方登录表，生成token返回
    data = {"data": {"userid": user.id, "exp": int(time.time())}}
    token = myjwt.jwt_encode(data)
    return redirect("http://localhost:8080/#/updataToken?userid=" + str(user.id) + "&token=" + token)
